import 'package:animal/model/models.dart';
import 'package:animal/network/api.dart';
import 'package:animal/ui/friend/NWApi.dart';
import 'package:animal/ui/friend/model/friend_addply_num_model.dart';
import 'package:animal/ui/friend/model/friend_model.dart';
import 'package:animal/ui/friend/page/add_friend_page.dart';
import 'package:animal/ui/friend/page/group_list_page.dart';
import 'package:animal/ui/friend/page/new_friend_page.dart';
import 'package:animal/ui/friend/page/search_friend_page.dart';
import 'package:animal/utils/index.dart';
import 'package:animal/widgets/PageStateWidget.dart';
import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class FriendListController extends GetxController{
  //好友申请数量
  RxInt applyNum = 0.obs;

  List<FriendModel> contactList = [];

  @override
  void onInit() {
    HttpManager.api = ChatApi.baseChatApi;
    HttpManager().initDio();
    super.onInit();
    getFriendList();
    friendApplyNum();
  }

  void _handleList(List<FriendModel> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].friendNickName!);
      String tag = pinyin.substring(0, 1).toUpperCase();
      // list[i].friendNickName = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(contactList);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(contactList);
  }

  ///前往搜索好友页面
  void gotoSearch(){
    Get.to(SearchFriendPage());
  }

  ///前往添加好友页面
  void gotoAddFriend(){
    Get.to(AddFriendPage());
  }

  ///前往新朋友
  void gotoNewFriend(){
    Get.to(NewFriendPage());
  }

  ///前往新朋友
  void gotoGroup(){
    Get.to(GroupListPage());
  }

  //列表状态
  var pageState = PageState.loading.obs;

  //好友列表
  var data = <FriendModel>[].obs;

  ///获取好友列表
  void getFriendList(){
    HttpManager().get<List<FriendModel>>(ChatApi.chatFriendPage,queryParameters: {}).listen((value) {
      data.addAll(value.data!);
      if(data.isNotEmpty){
        for(int i = 0;i<data.length;i++){
          contactList.add(data[i]);
        }
      }
      _handleList(contactList);
      pageState.value = data.isEmpty?PageState.empty:PageState.none;
    },onError: (err){
      pageState.value =  PageState.error;
      debugPrint(err.message);
    });
  }

  ///获取好友申请数量
  void friendApplyNum(){
    HttpManager().get<FriendAddplyNumModel>(ChatApi.friendApplyNum,queryParameters: {}).listen((value) {
      applyNum.value = value.data!.data!;
    },onError: (err){
      debugPrint(err.message);
    });
  }
}